package com.sofwin.shiro;

import java.util.List;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.sofwin.pojo.SUser;
import com.sofwin.service.RoleService;
import com.sofwin.service.UserService;

public class UserRealm extends AuthorizingRealm {

	private UserService userService;
	private RoleService roleService;
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// 获取用户
		String userName = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();		// 根据用户名查询用户
		SUser user = new SUser();
		user.setUserName(userName);
		// 包含有角色id
		
		user = userService.selectUserByUserNameAndPwd(user);
		// 通过角色id 可以获取到所有的权限
		authorizationInfo.addRole(String.valueOf(user.getRoleId()));
		// String 类型的权限
		// type=0 url user/add user/edit user/delete
		// resource_url 权限名称
		// 将该角色所拥有的所有权限添加到SimpleAuthorizationInfo
		List<String> permissions =roleService.selectPermissionByRoleId(user.getRoleId());
		// 将所有三级权限全部放入到授权对象中
		for(String permission:permissions) {
		authorizationInfo.addStringPermission(permission);
		}
		return authorizationInfo;
	}
/**
 * 认证
 * @return
 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName=null;
		String pwd=null;
		UsernamePasswordToken token1 = (UsernamePasswordToken)token;
		try {
			userName = token1.getUsername();
			pwd = String.valueOf(token1.getPassword());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		SUser user = new SUser();
		user.setUserName(userName);
		SUser user2 = userService.selectUserByUserNameAndPwd(user);
		user.setPwd(pwd);
		SUser user3 = userService.selectUserByUserNameAndPwd(user);
		if(user2==null) {
			throw new UnknownAccountException();
		}
		if(user3==null) {
			throw new IncorrectCredentialsException();
		}
		
		return new SimpleAuthenticationInfo(userName,pwd,"userReal");
	
	}
public void setUserService(UserService userService) {
	this.userService = userService;
}
public void setRoleService(RoleService roleService) {
	this.roleService = roleService;
}
	

}
